﻿#include <stdio.h>
#include "NavHelper.h"
#include "ResLoader.h"
#include "PathFinder.h"
#include "../Detour/DetourNavMeshQuery.h"

dtNavMesh* NavHelper::GetNavMesh(std::string filepath)
{
	
	std::string name = filepath;
	NavmeshMap::iterator iter = m_navmeshMap.find(name);
	if (iter != m_navmeshMap.end())
	{
		return iter->second;
	}
	dtNavMesh* navMesh = ResLoader::LoadNaviMesh(name);
	if (!navMesh)
	{
		return NULL;
	}
	m_navmeshMap.insert(std::make_pair(name, navMesh));
	return navMesh;
}

PathFinder* NavHelper::GetFinder(dtNavMesh* navmesh)
{
	dtNavMeshQuery* navQuery = dtAllocNavMeshQuery();
	if (dtStatusFailed(navQuery->init(navmesh, 2048)))
	{
		return NULL;
	}
	PathFinder* finder = new PathFinder(navmesh, navQuery);
	return finder;
}

void NavHelper::ReleaseMap()
{
	for (NavmeshMap::iterator iter = m_navmeshMap.begin(); iter != m_navmeshMap.end(); ++iter)
	{
		dtFreeNavMesh(iter->second);
		//SAFE_DELETE(iter->second);
	}
	m_navmeshMap.clear();
	ReleaseMapTO();
}

float* NavHelper::FindPath(PathFinder* finder, float& sposX, float& sposY, float& sposZ,
	float& eposX, float& eposY, float& eposZ, int* count)
{
	*count = 0;
	if (!finder->Find(sposX, sposY, sposZ, eposX, eposY, eposZ))
	{
		return nullptr;
	}
	return finder->GetPath(count);
}

float* NavHelper::CalcNear(PathFinder* finder, float& sposX, float& sposY, float& sposZ, int* count)
{
	*count = 0;
	if (!finder->CalcNear(sposX, sposY, sposZ))
	{
		return nullptr;
	}
	return finder->GetNear(count);
}

float* NavHelper::CalcRaycast(PathFinder* finder, float& sposX, float& sposY, float& sposZ, float& eposX, float& eposY, float& eposZ,int* count)
{
	*count = 0;
	if (!finder->CalcRaycast(sposX, sposY, sposZ, eposX, eposY, eposZ))
	{
		return nullptr;
	}

	return finder->GetRaycast(count);
}
